const User = require('../models/User');
const { asyncHandler } = require('../middleware/errorMiddleware');
const logger = require('../utils/logger');

// @desc    获取用户列表
// @route   GET /api/users
// @access  Private/Admin
const getUsers = asyncHandler(async (req, res) => {
  const page = parseInt(req.query.page) || 1;
  const limit = parseInt(req.query.limit) || 10;
  const filters = {
    role: req.query.role,
    status: req.query.status,
    search: req.query.search
  };

  // 移除空值
  Object.keys(filters).forEach(key => {
    if (!filters[key]) delete filters[key];
  });

  const result = await User.getList(page, limit, filters);

  res.json({
    success: true,
    data: result,
    message: 'Users retrieved successfully'
  });
});

// @desc    获取单个用户信息
// @route   GET /api/users/:id
// @access  Private/Admin
const getUserById = asyncHandler(async (req, res) => {
  const user = await User.findById(req.params.id);

  if (!user) {
    res.status(404);
    throw new Error('User not found');
  }

  res.json({
    success: true,
    data: {
      user: user.toJSON()
    },
    message: 'User retrieved successfully'
  });
});

// @desc    更新用户信息
// @route   PUT /api/users/:id
// @access  Private/Admin or Own Profile
const updateUser = asyncHandler(async (req, res) => {
  const userId = req.params.id;
  const { username, email, avatar, status, role } = req.body;

  // 检查权限：管理员可以更新任何用户，普通用户只能更新自己的信息
  if (req.user.role !== 'admin' && req.user.id != userId) {
    res.status(403);
    throw new Error('Access denied - can only update own profile');
  }

  const user = await User.findById(userId);
  if (!user) {
    res.status(404);
    throw new Error('User not found');
  }

  // 普通用户不能修改角色和状态
  const updateData = { username, email, avatar };
  if (req.user.role === 'admin') {
    if (status) updateData.status = status;
    if (role) updateData.role = role;
  }

  // 移除空值
  Object.keys(updateData).forEach(key => {
    if (updateData[key] === undefined || updateData[key] === '') {
      delete updateData[key];
    }
  });

  if (Object.keys(updateData).length === 0) {
    res.status(400);
    throw new Error('No valid fields to update');
  }

  try {
    const updatedUser = await user.update(updateData);
    
    logger.info(`User updated: ${updatedUser.email} by ${req.user.email}`);

    res.json({
      success: true,
      data: {
        user: updatedUser.toJSON()
      },
      message: 'User updated successfully'
    });
  } catch (error) {
    logger.error('User update error:', error);
    res.status(400);
    throw new Error(error.message);
  }
});

// @desc    更改密码
// @route   PUT /api/users/:id/password
// @access  Private (Own Profile Only)
const changePassword = asyncHandler(async (req, res) => {
  const userId = req.params.id;
  const { currentPassword, newPassword } = req.body;

  // 只能修改自己的密码
  if (req.user.id != userId) {
    res.status(403);
    throw new Error('Access denied - can only change own password');
  }

  const user = await User.findById(userId);
  if (!user) {
    res.status(404);
    throw new Error('User not found');
  }

  try {
    await user.changePassword(currentPassword, newPassword);
    
    logger.info(`Password changed for user: ${user.email}`);

    res.json({
      success: true,
      message: 'Password changed successfully'
    });
  } catch (error) {
    logger.error('Password change error:', error);
    res.status(400);
    throw new Error(error.message);
  }
});

// @desc    删除用户
// @route   DELETE /api/users/:id
// @access  Private/Admin
const deleteUser = asyncHandler(async (req, res) => {
  const userId = req.params.id;

  // 不能删除自己
  if (req.user.id == userId) {
    res.status(400);
    throw new Error('Cannot delete your own account');
  }

  const user = await User.findById(userId);
  if (!user) {
    res.status(404);
    throw new Error('User not found');
  }

  await user.delete();
  
  logger.info(`User deleted: ${user.email} by ${req.user.email}`);

  res.json({
    success: true,
    message: 'User deleted successfully'
  });
});

// @desc    获取当前用户的个人资料
// @route   GET /api/users/profile
// @access  Private
const getProfile = asyncHandler(async (req, res) => {
  const user = await User.findById(req.user.id);

  if (!user) {
    res.status(404);
    throw new Error('User not found');
  }

  res.json({
    success: true,
    data: {
      user: user.toJSON()
    },
    message: 'Profile retrieved successfully'
  });
});

// @desc    更新当前用户的个人资料
// @route   PUT /api/users/profile
// @access  Private
const updateProfile = asyncHandler(async (req, res) => {
  const { username, email, avatar } = req.body;
  
  const user = await User.findById(req.user.id);
  if (!user) {
    res.status(404);
    throw new Error('User not found');
  }

  const updateData = {};
  if (username) updateData.username = username;
  if (email) updateData.email = email;
  if (avatar !== undefined) updateData.avatar = avatar;

  if (Object.keys(updateData).length === 0) {
    res.status(400);
    throw new Error('No valid fields to update');
  }

  try {
    const updatedUser = await user.update(updateData);
    
    logger.info(`Profile updated: ${updatedUser.email}`);

    res.json({
      success: true,
      data: {
        user: updatedUser.toJSON()
      },
      message: 'Profile updated successfully'
    });
  } catch (error) {
    logger.error('Profile update error:', error);
    res.status(400);
    throw new Error(error.message);
  }
});

// @desc    获取用户统计信息
// @route   GET /api/users/stats
// @access  Private/Admin
const getUserStats = asyncHandler(async (req, res) => {
  const { query } = require('../config/database');
  
  const stats = await query(`
    SELECT 
      COUNT(*) as total_users,
      SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active_users,
      SUM(CASE WHEN status = 'inactive' THEN 1 ELSE 0 END) as inactive_users,
      SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) as admin_users,
      SUM(CASE WHEN DATE(created_at) = CURDATE() THEN 1 ELSE 0 END) as today_registrations,
      SUM(CASE WHEN DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as week_registrations
    FROM users 
    WHERE status != 'deleted'
  `);

  res.json({
    success: true,
    data: {
      stats: stats[0]
    },
    message: 'User statistics retrieved successfully'
  });
});

module.exports = {
  getUsers,
  getUserById,
  updateUser,
  changePassword,
  deleteUser,
  getProfile,
  updateProfile,
  getUserStats
};